/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package NetBeansProjects.Indexer3.src.util.docsCache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author Ivan
 */
public class CachedDocument {
    int id;
    DocPosition location;
    StringBuilder contents;
    String basePath;

    /**
     * 
     * @param cacheEntry contains the term needed.
     * @param  holds the base path of the document handled.
     * @return information needed to fetch the document.
     */
    public static CachedDocument forCacheEntry(String cacheEntry, String basePath){
        String[] components = cacheEntry.split("=");
        int id = Integer.parseInt(components[0]);
        DocPosition loctn = DocPosition.fromString(components[1]);
        return new CachedDocument(id, loctn, basePath);
    }


    /**
     * 
     * @return Doc ID is returned.
     */
    public int getId(){
        return id;
    }


    /**
     * 
     * @return content of file found according to terms is provided
     * @throws FileNotFoundException
     * @throws IOException
     */
    public String getContents() throws FileNotFoundException, IOException{
        if(contents.length() != 0){
            return contents.toString();
        }

        String path = basePath + "\\" + location.getFile();
        int firstLine = location.getDocStartLine();
        int numLines = location.getDocEndLine() - firstLine;
        BufferedReader reader;
        reader = new BufferedReader(new FileReader(new File(path)));

        String line = "";

        // skip to the first line
        while(--firstLine > 0){
            reader.readLine();
        }

        // read document
        while(numLines-- >= 0){
            line = reader.readLine();
            if(line != null){
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }else{
                throw new IOException();
            }
        }
        reader.close();

        return contents.toString();
    }


    /**
     * Reinitializes the StringBuilder. (location where resulting text is stored)
     */
    public void refresh(){
        contents.setLength(0);
    }



    
    /**
     * Will output the content of the StringBuilder.
     */
    @Override
    public String toString(){
        return contents.toString();
    }

	/**
	 * 
	 * @param id holds the doc id.
	 * @param location holds the location of the doc id provided
	 * @param basePath holds the base path of the document handled
	 */
    private CachedDocument(int id, DocPosition location, String basePath){
        this.id = id;
        this.location = location;
        this.basePath = basePath;
        this.contents = new StringBuilder();
    }
}
